package com.jason.kotlin.gank.viewmodel

import android.app.Application
import androidx.lifecycle.viewModelScope
import com.jason.kotlin.gank.api.GankService
import com.jason.kotlin.gank.model.GankDataBean
import com.jason.kotlin.gank.repository.GankApiImpl
import com.jason.library.common.base.BasePageViewModel
import com.jason.library.common.base.DataWrapper
import kotlinx.coroutines.launch

/**
 * @description: GankSearchViewModel
 *
 * @author ChenBaoyang
 * @date 4/20/21 16:40
 */
class GankSearchViewModel(application: Application) : BasePageViewModel<GankDataBean>(application)  {

    private var gankApi = GankApiImpl()

    fun initData(dataBeans: MutableList<GankDataBean>) {
        data.value = DataWrapper.success(dataBeans)
    }

    var keyword: String = ""

    override fun loadData(page: Int) {
        viewModelScope.launch {
            try {
                val response = gankApi.getSearchData(keyword, page, 20)
                if(isFirstPage() && response.data.isNullOrEmpty()) {
                    showEmpty()
                }else{
                    data.postValue(DataWrapper.success(response.data))
                    showContent()
                }

            }catch (e: Exception) {
                showError(e.toString())
            }
        }
    }

}